using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using WpfMedia = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Windows.Interop;
using System.Windows.Media;
using Microsoft.Extensions.DependencyInjection;
using TxTReader.Core;
using TxTReader.Services;
using TxTReader.UI;

namespace TxTReader
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly MemoryMappedFileReader _fileReader;
        private readonly SettingsService _settingsService;
        private readonly HistoryService _historyService;
        private string _currentFilePath = string.Empty;
        private TextBlockTextControl? _textBlockTextControl;
        
        // 命令属性
        public ICommand OpenFileCommand { get; }
        public ICommand CloseFileCommand { get; }
        public ICommand ExitCommand { get; }
        public ICommand SearchCommand { get; }
        public ICommand FindNextCommand { get; }
        public ICommand FindPreviousCommand { get; }
        public ICommand SettingsCommand { get; }
        public ICommand GoToLineCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        
        // 滚动防抖相关
        private readonly Timer _scrollDebounceTimer;
        private const int ScrollDebounceDelay = 500; // 500ms防抖延迟

        public MainWindow()
        {
            InitializeComponent();
            
            // 设置窗口图标（文档图标）
            SetWindowIcon();
            
            // 初始化命令
            OpenFileCommand = new RelayCommand(async () => await OpenFile());
            CloseFileCommand = new RelayCommand(() => CloseFile());
            ExitCommand = new RelayCommand(() => Close());
            SearchCommand = new RelayCommand(() => OnSearchClick(null, null));
            FindNextCommand = new RelayCommand(() => OnFindNextClick(null, null));
            FindPreviousCommand = new RelayCommand(() => OnFindPreviousClick(null, null));
            SettingsCommand = new RelayCommand(() => OnSettingsClick(null, null));
            GoToLineCommand = new RelayCommand(() => OnGoToLineClick(null, null));
            PreviousPageCommand = new RelayCommand(() => OnPreviousPageClick(null, null));
            NextPageCommand = new RelayCommand(() => OnNextPageClick(null, null));
            
            // 设置数据上下文
            DataContext = this;
            
            // 初始化文本控件
            InitializeTextControl();
            
            // 初始化服务
            _fileReader = new MemoryMappedFileReader();
            _settingsService = new SettingsService();
            _historyService = new HistoryService();

            // 初始化滚动防抖定时器
            _scrollDebounceTimer = new Timer(OnScrollDebounceTimerElapsed, null, Timeout.Infinite, Timeout.Infinite);

            // 设置拖放
            AllowDrop = true;
            DragEnter += OnDragEnter;
            DragOver += OnDragOver;
            Drop += OnDrop;

            // 绑定Loaded事件来初始化历史记录菜单
            Loaded += OnWindowLoaded;
            Closing += OnClosing;
            _fileReader.FileOpened += OnFileOpened;
            _fileReader.EncodingChanged += OnEncodingChanged;
            
            // 绑定鼠标滚轮事件（移除，改为绑定TextBlockTextControl的滚动事件）
            // MouseWheel += OnMouseWheel;

            // 应用设置
            ApplySettings();
            
            // 应用保存的主题，如果没有则使用默认主题
            var savedTheme = _settingsService.Settings.CurrentTheme;
            if (string.IsNullOrEmpty(savedTheme))
            {
                savedTheme = "Classic"; // 默认主题
            }
            ApplyTheme(savedTheme);
            UpdateThemeMenuStates(savedTheme);
        }

        private void InitializeTextControl()
        {
            // 创建TextBlock文本控件并添加到主内容区域
            _textBlockTextControl = new TextBlockTextControl();
            TextContentPresenter.Content = _textBlockTextControl;
            
            // 绑定滚动事件
            _textBlockTextControl.Scrolled += OnTextControlScrolled;
            
            // 添加键盘事件处理
            this.KeyDown += OnKeyDown;
        }


        // XAML事件处理方法
        private void OnOpenFileClick(object sender, RoutedEventArgs e)
        {
            OpenFile();
        }

        private void OnCloseFileClick(object sender, RoutedEventArgs e)
        {
            CloseFile();
        }

        private void OnExitClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 窗口关闭时保存阅读进度
        /// </summary>
        private async void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 保存当前阅读进度
            if (!string.IsNullOrEmpty(_currentFilePath))
            {
                await UpdateHistoryPositionAsync();
            }
        }

        private void OnSearchClick(object sender, RoutedEventArgs e)
        {
            OpenSearch();
        }

        private void OnFindNextClick(object sender, RoutedEventArgs e)
        {
            FindNext();
        }

        private void OnFindPreviousClick(object sender, RoutedEventArgs e)
        {
            FindPrevious();
        }

        private void OnSettingsClick(object sender, RoutedEventArgs e)
        {
            OpenSettings();
        }

        private void OnGoToLineClick(object sender, RoutedEventArgs e)
        {
            OpenGoToLine();
        }

        private void OnToggleToolbarClick(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem)
            {
                MainToolBar.Visibility = (menuItem.IsChecked == true) ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        private void OnToggleStatusBarClick(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem)
            {
                StatusBar.Visibility = (menuItem.IsChecked == true) ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        private async void OnToggleLineNumberClick(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem)
            {
                bool showLineNumbers = menuItem.IsChecked == true;
                
                // 更新设置
                var settings = _settingsService.Settings;
                settings.ShowLineNumbers = showLineNumbers;
                await _settingsService.UpdateSettingsAsync(settings);
                
                // 应用到文本控件
                if (_textBlockTextControl != null)
                {
                    _textBlockTextControl.SetLineNumberSettings(showLineNumbers);
                }
                
                System.Diagnostics.Debug.WriteLine($"OnToggleLineNumberClick: 行号显示 = {showLineNumbers}");
            }
        }

        private async void OnThemeClick(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Tag is string themeName)
            {
                ApplyTheme(themeName);
                UpdateThemeMenuStates(themeName);
                
                // 保存主题设置
                var settings = _settingsService.Settings;
                settings.CurrentTheme = themeName;
                await _settingsService.UpdateSettingsAsync(settings);
                
                System.Diagnostics.Debug.WriteLine($"OnThemeClick: 主题已切换并保存 - {themeName}");
            }
        }

        private void ApplyTheme(string themeName)
        {
            var theme = ThemeService.Themes[themeName];
            if (theme == null) return;

            // 应用窗口主题
            Background = theme.WindowBackground;
            // 不更改字体大小，只更改颜色
            // FontFamily = new FontFamily(theme.FontFamily);

            // 应用菜单主题
            MainMenu.Background = theme.MenuBackground;
            MainMenu.Foreground = theme.MenuForeground;
            // 子菜单背景/边框
            Application.Current.Resources["MenuItem.SubmenuBackground"] = theme.MenuBackground;
            Application.Current.Resources["MenuItem.SubmenuBorder"] = theme.MenuForeground;

            // 应用工具栏主题（Border没有Foreground属性，按钮颜色通过ApplyToolBarButtonColors设置）
            MainToolBar.Background = theme.ToolBarBackground;

            // 应用工具栏按钮图标颜色
            ApplyToolBarButtonColors(theme.MenuForeground);

            // 应用状态栏主题
            StatusBar.Background = theme.StatusBarBackground;
            foreach (var child in StatusBar.Children)
            {
                if (child is Label label)
                {
                    label.Foreground = theme.StatusBarForeground;
                }
            }

            // 应用文本区域主题（只更改颜色，不更改字体大小）
            if (_textBlockTextControl != null)
            {
                _textBlockTextControl.Background = theme.TextBackground;
                _textBlockTextControl.Foreground = theme.TextForeground;
                // 不更改字体大小
                // _textBlockTextControl.FontFamily = new FontFamily(theme.FontFamily);
                // _textBlockTextControl.FontSize = theme.FontSize;
            }

            // 同步保存到设置（仅颜色），确保后续打开文件沿用主题颜色
            try
            {
                var settings = _settingsService.Settings;
                if (theme.TextForeground is SolidColorBrush fgBrush)
                {
                    settings.DefaultForegroundColor = fgBrush.Color.ToString();
                }
                if (theme.TextBackground is SolidColorBrush bgBrush)
                {
                    settings.DefaultBackgroundColor = bgBrush.Color.ToString();
                }
                // 异步保存，避免阻塞UI
                _ = _settingsService.UpdateSettingsAsync(settings);
            }
            catch { }

            // 更新ThemeService中的当前主题（不保存到设置，由OnThemeClick处理）
            ThemeService.SetTheme(themeName);

            // 应用全局滚动条样式
            var scrollBarStyle = new Style(typeof(System.Windows.Controls.Primitives.ScrollBar));
            scrollBarStyle.Setters.Add(new Setter(BackgroundProperty, theme.StatusBarBackground));
            scrollBarStyle.Setters.Add(new Setter(ForegroundProperty, theme.StatusBarForeground));
            Application.Current.Resources[typeof(System.Windows.Controls.Primitives.ScrollBar)] = scrollBarStyle;
        }

        private void ApplyToolBarButtonColors(System.Windows.Media.Brush foregroundBrush)
        {
            // 遍历工具栏中的所有按钮，更新其TextBlock的Foreground
            // MainToolBar现在是Border，包含一个StackPanel
            if (MainToolBar.Child is StackPanel stackPanel)
            {
                foreach (var child in stackPanel.Children)
                {
                    if (child is Button button)
                    {
                        if (button.Content is TextBlock textBlock)
                        {
                            textBlock.Foreground = foregroundBrush;
                        }
                    }
                }
            }
        }

        private void UpdateThemeMenuStates(string selectedTheme)
        {
            // 清除所有主题菜单项的选中状态
            ClassicThemeMenuItem.IsChecked = false;
            PureWhiteThemeMenuItem.IsChecked = false;
            CreamEyeCareThemeMenuItem.IsChecked = false;
            GreenTerminalThemeMenuItem.IsChecked = false;
            AmberThemeMenuItem.IsChecked = false;
            BlueThemeMenuItem.IsChecked = false;
            DarkEyeCareThemeMenuItem.IsChecked = false;

            // 选中当前主题
            switch (selectedTheme)
            {
                case "Classic":
                    ClassicThemeMenuItem.IsChecked = true;
                    break;
                case "PureWhite":
                    PureWhiteThemeMenuItem.IsChecked = true;
                    break;
                case "CreamEyeCare":
                    CreamEyeCareThemeMenuItem.IsChecked = true;
                    break;
                case "GreenTerminal":
                    GreenTerminalThemeMenuItem.IsChecked = true;
                    break;
                case "Amber":
                    AmberThemeMenuItem.IsChecked = true;
                    break;
                case "Blue":
                    BlueThemeMenuItem.IsChecked = true;
                    break;
                case "DarkEyeCare":
                    DarkEyeCareThemeMenuItem.IsChecked = true;
                    break;
            }
        }

        private async void OnNextPageClick(object sender, RoutedEventArgs e)
        {
            LoadNextPage();
            await UpdateHistoryPositionAsync();
        }

        private async void OnPreviousPageClick(object sender, RoutedEventArgs e)
        {
            LoadPreviousPage();
            await UpdateHistoryPositionAsync();
        }

        /// <summary>
        /// 更新历史记录中的当前位置
        /// </summary>
        private async Task UpdateHistoryPositionAsync()
        {
            // 检查是否启用历史记录
            if (!_settingsService.Settings.EnableHistory)
            {
                return;
            }
            
            if (!string.IsNullOrEmpty(_currentFilePath) && _textBlockTextControl != null)
            {
                try
                {
                    // 获取当前阅读的行号（这里需要从TextBlockTextControl获取）
                    var currentLine = _textBlockTextControl.GetCurrentViewLine();
                    await _historyService.UpdateLineNumberAsync(_currentFilePath, currentLine);
                    
                    // 更新历史记录菜单
                    Dispatcher.Invoke(() =>
                    {
                        InitializeHistoryMenu();
                    });
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"更新历史记录位置失败: {ex.Message}");
                }
            }
        }

        private async void OnEncodingClick(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Tag is string encodingName)
            {
                // 更新菜单项的选中状态（单选）
                UpdateEncodingMenuStates(encodingName);
                
                // 保存选择的编码到设置中
                var settings = _settingsService.Settings;
                settings.SelectedEncoding = encodingName;
                await _settingsService.UpdateSettingsAsync(settings);
                
                // 如果不是自动选择，则立即更改编码
                if (encodingName != "Auto")
                {
                    ChangeEncodingByName(encodingName);
                }
            }
        }

        private void OnAboutClick(object sender, RoutedEventArgs e)
        {
            var aboutWindow = new UI.AboutWindow
            {
                Owner = this
            };
            aboutWindow.ShowDialog();
        }


        /// <summary>
        /// 更新状态栏信息
        /// </summary>
        public void UpdateStatusBar()
        {
            var settings = _settingsService.Settings;
            
            // 检查状态栏是否被用户手动隐藏
            if (FindName("StatusBar") is StackPanel statusBar)
            {
                // 如果状态栏被隐藏且没有文件打开，保持隐藏状态
                if (statusBar.Visibility == Visibility.Collapsed && !_fileReader.IsFileOpen)
                {
                    return;
                }
                // 如果有文件打开，确保状态栏显示
                else if (_fileReader.IsFileOpen && statusBar.Visibility == Visibility.Collapsed)
                {
                    statusBar.Visibility = Visibility.Visible;
                }
            }
            
            // 更新文件名
            if (FindName("FileNameLabel") is Label fileNameLabel)
            {
                fileNameLabel.Visibility = settings.ShowFileName ? Visibility.Visible : Visibility.Collapsed;
                if (_fileReader.IsFileOpen)
                {
                    var fileName = Path.GetFileName(_currentFilePath);
                    fileNameLabel.Content = fileName;
                }
                else
                {
                    fileNameLabel.Content = "就绪";
                }
            }

            // 更新可见行数
            if (FindName("VisibleLinesLabel") is Label visibleLinesLabel)
            {
                visibleLinesLabel.Visibility = settings.ShowVisibleLines ? Visibility.Visible : Visibility.Collapsed;
                if (_textBlockTextControl != null && _fileReader.IsFileOpen)
                {
                    var visibleLines = _textBlockTextControl.GetVisibleLinesPerScreen();
                    visibleLinesLabel.Content = $"[{visibleLines}]";
                }
                else
                {
                    visibleLinesLabel.Content = "[0]";
                }
            }

            // 更新当前页范围
            if (FindName("CurrentRangeLabel") is Label currentRangeLabel)
            {
                currentRangeLabel.Visibility = settings.ShowLoadedRange ? Visibility.Visible : Visibility.Collapsed;
                if (_textBlockTextControl != null && _fileReader.IsFileOpen)
                {
                    var displayRange = _textBlockTextControl.GetCurrentDisplayRange();
                    currentRangeLabel.Content = $"[{displayRange}]";
                }
                else
                {
                    currentRangeLabel.Content = "[0-0]";
                }
            }

            // 更新总行数
            if (FindName("TotalLinesLabel") is Label totalLinesLabel)
            {
                totalLinesLabel.Visibility = settings.ShowTotalLines ? Visibility.Visible : Visibility.Collapsed;
                if (_fileReader.IsFileOpen)
                {
                    totalLinesLabel.Content = _fileReader.TotalLines.ToString("N0");
                }
                else
                {
                    totalLinesLabel.Content = "0";
                }
            }

            // 更新分隔符的显示状态
            UpdateSeparatorVisibility(settings);
        }

        /// <summary>
        /// 更新分隔符的显示状态
        /// </summary>
        private void UpdateSeparatorVisibility(AppSettings settings)
        {
            // 分隔符1：文件名和可见行数之间
            if (FindName("Separator1") is Label separator1)
            {
                separator1.Visibility = (settings.ShowFileName && settings.ShowVisibleLines) ? Visibility.Visible : Visibility.Collapsed;
            }

            // 分隔符2：当前页范围和总行数之间
            if (FindName("Separator2") is Label separator2)
            {
                separator2.Visibility = (settings.ShowLoadedRange && settings.ShowTotalLines) ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 窗口加载完成事件
        /// </summary>
        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"OnWindowLoaded: 窗口加载完成，开始初始化历史记录菜单");
            InitializeHistoryMenu();
            InitializeWordWrapMenus();
            InitializeEncodingMenus();
            InitializeLineNumberMenu();
            
            // 确保窗口获得焦点以接收键盘事件
            this.Focus();
        }

        /// <summary>
        /// 初始化行号菜单
        /// </summary>
        private void InitializeLineNumberMenu()
        {
            var settings = _settingsService.Settings;
            LineNumberMenuItem.IsChecked = settings.ShowLineNumbers;
        }
        private void InitializeEncodingMenus()
        {
            var settings = _settingsService.Settings;
            UpdateEncodingMenuStates(settings.SelectedEncoding);
        }

        /// <summary>
        /// 初始化历史记录菜单
        /// </summary>
        private void InitializeHistoryMenu()
        {
            System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 开始初始化历史记录菜单，当前线程ID: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
            System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 是否在UI线程: {Dispatcher.CheckAccess()}");
            
            var historyMenu = FindName("HistoryMenu") as MenuItem;
            if (historyMenu == null) 
            {
                System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 找不到HistoryMenu控件");
                return;
            }

            System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 找到HistoryMenu控件，开始清空现有菜单项");
            // 清空现有菜单项
            historyMenu.Items.Clear();

            // 检查是否启用历史记录
            if (!_settingsService.Settings.EnableHistory)
            {
                System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 历史记录已禁用");
                var disabledItem = new MenuItem
                {
                    Header = "历史记录已禁用",
                    IsEnabled = false
                };
                historyMenu.Items.Add(disabledItem);
                return;
            }

            // 获取历史记录
            var history = _historyService.History.Take(10).ToList(); // 最多显示10条记录
            System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 获取到 {history.Count} 条历史记录");

            if (history.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 没有历史记录，显示提示");
                // 没有历史记录时显示提示
                var noHistoryItem = new MenuItem
                {
                    Header = "暂无历史记录",
                    IsEnabled = false
                };
                historyMenu.Items.Add(noHistoryItem);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 开始添加历史记录项");
                // 添加历史记录项
                foreach (var item in history)
                {
                    System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 添加历史记录项 - {item.FileName}");
                    var menuItem = new MenuItem
                    {
                        Header = $"{item.FileName} (第{item.LineNumber}行)",
                        Tag = item.FilePath,
                        ToolTip = $"路径: {item.FilePath}\n最后打开: {item.LastOpened:yyyy-MM-dd HH:mm:ss}"
                    };
                    menuItem.Click += OnHistoryItemClick;
                    historyMenu.Items.Add(menuItem);
                }

                // 添加分隔符和清除历史记录选项
                historyMenu.Items.Add(new Separator());
                var clearHistoryItem = new MenuItem
                {
                    Header = "清除所有历史记录",
                    Foreground = System.Windows.Media.Brushes.Red
                };
                clearHistoryItem.Click += OnClearHistoryClick;
                historyMenu.Items.Add(clearHistoryItem);
                System.Diagnostics.Debug.WriteLine($"InitializeHistoryMenu: 历史记录菜单初始化完成");
            }
        }

        /// <summary>
        /// 初始化换行策略菜单
        /// </summary>
        private void InitializeWordWrapMenus()
        {
            System.Diagnostics.Debug.WriteLine($"InitializeWordWrapMenus: 开始初始化换行策略菜单");
            
            // 根据当前设置初始化菜单状态
            var currentWordWrapMode = _settingsService.Settings.WordWrapMode;
            UpdateWordWrapMenuStates(currentWordWrapMode);
            
            System.Diagnostics.Debug.WriteLine($"InitializeWordWrapMenus: 换行策略菜单初始化完成，当前模式 = {currentWordWrapMode}");
        }

        /// <summary>
        /// 历史记录项点击事件
        /// </summary>
        private async void OnHistoryItemClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"OnHistoryItemClick: 点击了历史记录项");
            
            if (sender is MenuItem menuItem && menuItem.Tag is string filePath)
            {
                System.Diagnostics.Debug.WriteLine($"OnHistoryItemClick: 文件路径 = {filePath}");
                try
                {
                    await OpenFileFromPath(filePath);
                    System.Diagnostics.Debug.WriteLine($"OnHistoryItemClick: 文件打开成功");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"OnHistoryItemClick: 打开文件失败 - {ex.Message}");
                    MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"OnHistoryItemClick: 无法获取文件路径");
            }
        }

        /// <summary>
        /// 清除历史记录点击事件
        /// </summary>
        private async void OnClearHistoryClick(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确定要清除所有历史记录吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    await _historyService.ClearHistoryAsync();
                    Dispatcher.Invoke(() =>
                    {
                        InitializeHistoryMenu(); // 重新初始化菜单
                    });
                    MessageBox.Show("历史记录已清除", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"清除历史记录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 从路径打开文件
        /// </summary>
        private async Task OpenFileFromPath(string filePath)
        {
            System.Diagnostics.Debug.WriteLine($"OpenFileFromPath: 开始打开文件 {filePath}");
            
            if (!File.Exists(filePath))
            {
                System.Diagnostics.Debug.WriteLine($"OpenFileFromPath: 文件不存在 {filePath}");
                MessageBox.Show($"文件不存在: {filePath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            System.Diagnostics.Debug.WriteLine($"OpenFileFromPath: 文件存在，添加到历史记录");
            // 添加到历史记录
            await _historyService.AddFileAsync(filePath);

            System.Diagnostics.Debug.WriteLine($"OpenFileFromPath: 开始打开文件");
            // 使用 LoadFileAsync 方法打开文件，确保应用用户选择的编码设置
            await LoadFileAsync(filePath);
            
            System.Diagnostics.Debug.WriteLine($"OpenFileFromPath: 文件打开完成，更新历史记录菜单");
            // 更新历史记录菜单
            Dispatcher.Invoke(() =>
            {
                InitializeHistoryMenu();
            });
        }

        private async Task OpenFile()
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                Title = "选择要打开的文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                await LoadFileAsync(openFileDialog.FileName);
            }
        }

        /// <summary>
        /// 检查并应用历史记录进度
        /// </summary>
        private async Task CheckAndApplyHistoryProgressAsync(string filePath)
        {
            if (!_settingsService.Settings.EnableHistory)
            {
                System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 历史记录已禁用，从第1行开始");
                return;
            }

            try
            {
                // 获取历史记录的行号
                System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 获取历史记录行号");
                var totalLines = (int)_fileReader.TotalLines;
                var historyLineNumber = _historyService.GetHistoryLineNumber(filePath, totalLines);
                System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 历史记录行号 = {historyLineNumber}, 总行数 = {totalLines}");
                
                // 添加到历史记录（如果不存在的话）
                System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 添加到历史记录");
                await _historyService.AddFileAsync(filePath);
                
                // 更新历史记录菜单
                Dispatcher.Invoke(() =>
                {
                    System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 更新历史记录菜单");
                    InitializeHistoryMenu();
                });
                
                // 如果历史记录的行号不是第1行，则跳转到该行
                if (historyLineNumber > 1)
                {
                    System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 开始跳转到第 {historyLineNumber} 行");
                    await _textBlockTextControl.JumpToLineAsync(historyLineNumber);
                    System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 跳转完成");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 加载第1页内容");
                    await _textBlockTextControl.LoadPageAsync(1);
                    System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 第1页内容加载完成");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"CheckAndApplyHistoryProgressAsync: 处理历史记录失败 - {ex.GetType().Name}: {ex.Message}");
                // 如果历史记录处理失败，至少加载第1页
                await _textBlockTextControl.LoadPageAsync(1);
            }
        }

        private async Task LoadFileAsync(string filePath)
        {
            try
            {
                // 如果有当前打开的文件，先保存其阅读进度
                if (!string.IsNullOrEmpty(_currentFilePath))
                {
                    await UpdateHistoryPositionAsync();
                }
                
                // 确定要使用的编码
                System.Text.Encoding? preferredEncoding = null;
                var settings = _settingsService.Settings;
                
                // 如果用户选择了特定编码（非自动选择），则使用该编码
                if (settings.SelectedEncoding != "Auto")
                {
                    preferredEncoding = EncodingDetector.GetEncodingByName(settings.SelectedEncoding);
                }
                else
                {
                    // 如果是自动选择，则优先使用历史记录中的编码
                    var historyEncoding = _historyService.GetHistoryEncoding(filePath);
                    if (!string.IsNullOrEmpty(historyEncoding))
                    {
                        preferredEncoding = EncodingDetector.GetEncodingByName(historyEncoding);
                    }
                    // 如果没有历史记录，则使用自动检测（preferredEncoding 保持为 null）
                }
                
                var success = await _fileReader.OpenFileAsync(filePath, preferredEncoding);
                if (success)
                {
                    _currentFilePath = filePath;
                    
                    // 设置文件读取器和应用字体设置
                    if (_textBlockTextControl != null)
                    {
                        await _textBlockTextControl.SetFileReaderAsync(_fileReader);
                        
                        // 应用当前字体设置
                        var fontSettings = _settingsService.Settings;
                        var fontFamily = new System.Windows.Media.FontFamily(fontSettings.DefaultFontFamily);
                        var fontSize = fontSettings.DefaultFontSize;
                        var foreground = System.Windows.Media.ColorConverter.ConvertFromString(fontSettings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                            ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                        var background = System.Windows.Media.ColorConverter.ConvertFromString(fontSettings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                            ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                        
                        _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                    }
                    
                    UpdateStatusBar();
                    UpdateEncodingMenuStates(settings.SelectedEncoding);
                    
                    // 检查并应用历史记录进度
                    await CheckAndApplyHistoryProgressAsync(filePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        

        private async void CloseFile()
        {
            // 保存当前阅读进度
            if (!string.IsNullOrEmpty(_currentFilePath))
            {
                await UpdateHistoryPositionAsync();
            }
            
            _fileReader.CloseFile();
            _currentFilePath = string.Empty;
            _textBlockTextControl?.Clear();
            UpdateStatusBar();
        }

        /// <summary>
        /// 载入上一页
        /// </summary>
        private async Task LoadPreviousPage()
        {
            if (_textBlockTextControl != null)
            {
                System.Diagnostics.Debug.WriteLine("MainWindow: 载入上一页");
                await _textBlockTextControl.LoadPreviousPageAsync();
            UpdateStatusBar();
            }
        }

        /// <summary>
        /// 载入下一页
        /// </summary>
        private async Task LoadNextPage()
        {
            if (_textBlockTextControl != null)
            {
                System.Diagnostics.Debug.WriteLine("MainWindow: 载入下一页");
                await _textBlockTextControl.LoadNextPageAsync();
                UpdateStatusBar();
            }
        }

        #region 键盘事件处理

        /// <summary>
        /// 键盘事件处理
        /// </summary>
        private async void OnKeyDown(object sender, KeyEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"OnKeyDown: {e.Key} pressed");
            
            if (_textBlockTextControl == null)
            {
                System.Diagnostics.Debug.WriteLine("OnKeyDown: _textBlockTextControl is null");
                return;
            }

            switch (e.Key)
            {
                // 1) PgUp/PgDn 翻一屏
                case Key.PageUp:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: PageUp - ScrollPageUp");
                    _textBlockTextControl.ScrollPageUp();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;
                case Key.PageDown:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: PageDown - ScrollPageDown");
                    _textBlockTextControl.ScrollPageDown();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;
                case Key.Space: // 空格向后翻一屏
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: Space - ScrollPageDown");
                    _textBlockTextControl.ScrollPageDown();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;

                // 2) 上下箭头按行滚动
                case Key.Up:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: Up - ScrollLineUp");
                    _textBlockTextControl.ScrollLineUp();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;
                case Key.Down:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: Down - ScrollLineDown");
                    _textBlockTextControl.ScrollLineDown();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;

                // 3) F11/F12 翻缓存页（主要方式，不受焦点影响）
                case Key.F11:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: F11 - LoadPreviousPage");
                    await LoadPreviousPage();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;
                case Key.F12:
                    System.Diagnostics.Debug.WriteLine("OnKeyDown: F12 - LoadNextPage");
                    await LoadNextPage();
                    await UpdateHistoryPositionAsync();
                    e.Handled = true;
                    break;
                
                // 4) 左右箭头按缓存页切换（备用方式，可能受焦点影响）
                case Key.Left:
                    // 只在窗口有焦点时才处理，避免与TextBox冲突
                    if (IsFocused || FocusManager.GetFocusedElement(this) == null)
                    {
                        System.Diagnostics.Debug.WriteLine("OnKeyDown: Left - LoadPreviousPage");
                        await LoadPreviousPage();
                        await UpdateHistoryPositionAsync();
                        e.Handled = true;
                    }
                    break;
                case Key.Right:
                    // 只在窗口有焦点时才处理，避免与TextBox冲突
                    if (IsFocused || FocusManager.GetFocusedElement(this) == null)
                    {
                        System.Diagnostics.Debug.WriteLine("OnKeyDown: Right - LoadNextPage");
                        await LoadNextPage();
                        await UpdateHistoryPositionAsync();
                        e.Handled = true;
                    }
                    break;
            }
        }

        #endregion

        #region 拖放处理

        private void OnDragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void OnDragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private async void OnDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length > 0)
                {
                    var filePath = files[0];
                    if (File.Exists(filePath))
                    {
                        await LoadFileAsync(filePath);
                    }
                }
            }
        }

        /// <summary>
        /// 更新编码菜单状态
        /// </summary>
        /// <param name="selectedEncoding">选中的编码名称，如果为null则根据当前文件编码更新</param>
        private void UpdateEncodingMenuStates(string? selectedEncoding = null)
        {
            // 清除所有菜单项的选中状态
            if (FindName("AutoSelectMenuItem") is MenuItem autoSelectMenuItem)
                autoSelectMenuItem.IsChecked = false;
            if (FindName("UTF8MenuItem") is MenuItem utf8MenuItem)
                utf8MenuItem.IsChecked = false;
            if (FindName("GB2312MenuItem") is MenuItem gb2312MenuItem)
                gb2312MenuItem.IsChecked = false;
            if (FindName("GBKMenuItem") is MenuItem gbkMenuItem)
                gbkMenuItem.IsChecked = false;
            if (FindName("Big5MenuItem") is MenuItem big5MenuItem)
                big5MenuItem.IsChecked = false;
            if (FindName("ASCIIMenuItem") is MenuItem asciiMenuItem)
                asciiMenuItem.IsChecked = false;
            
            // 如果有指定的编码，则选中对应的菜单项
            if (!string.IsNullOrEmpty(selectedEncoding))
            {
                switch (selectedEncoding)
                {
                    case "Auto":
                        if (FindName("AutoSelectMenuItem") is MenuItem autoItem)
                            autoItem.IsChecked = true;
                        break;
                    case "UTF-8":
                        if (FindName("UTF8MenuItem") is MenuItem utf8Item)
                            utf8Item.IsChecked = true;
                        break;
                    case "GB2312":
                        if (FindName("GB2312MenuItem") is MenuItem gb2312Item)
                            gb2312Item.IsChecked = true;
                        break;
                    case "GBK":
                        if (FindName("GBKMenuItem") is MenuItem gbkItem)
                            gbkItem.IsChecked = true;
                        break;
                    case "Big5":
                        if (FindName("Big5MenuItem") is MenuItem big5Item)
                            big5Item.IsChecked = true;
                        break;
                    case "ASCII":
                        if (FindName("ASCIIMenuItem") is MenuItem asciiItem)
                            asciiItem.IsChecked = true;
                        break;
                }
            }
            else if (_fileReader.IsFileOpen)
            {
                // 如果没有指定编码，则根据当前文件编码更新
                var currentEncodingName = EncodingDetector.GetEncodingDisplayName(_fileReader.CurrentEncoding);
                switch (currentEncodingName)
                {
                    case "UTF-8":
                        if (FindName("UTF8MenuItem") is MenuItem utf8Item)
                            utf8Item.IsChecked = true;
                        break;
                    case "GB2312":
                        if (FindName("GB2312MenuItem") is MenuItem gb2312Item)
                            gb2312Item.IsChecked = true;
                        break;
                    case "GBK":
                        if (FindName("GBKMenuItem") is MenuItem gbkItem)
                            gbkItem.IsChecked = true;
                        break;
                    case "Big5":
                        if (FindName("Big5MenuItem") is MenuItem big5Item)
                            big5Item.IsChecked = true;
                        break;
                    case "ASCII":
                        if (FindName("ASCIIMenuItem") is MenuItem asciiItem)
                            asciiItem.IsChecked = true;
                        break;
                    default:
                        // 如果检测到的编码不在列表中，则选中自动选择
                        if (FindName("AutoSelectMenuItem") is MenuItem autoItem)
                            autoItem.IsChecked = true;
                        break;
                }
            }
        }

        #endregion

        #region 编码操作

        private async void ChangeEncodingByName(string encodingName)
        {
            if (!string.IsNullOrEmpty(_currentFilePath))
            {
                try
                {
                    // 保存当前阅读进度
                    var currentPageNumber = _textBlockTextControl?.GetCurrentPageNumber() ?? 1;
                    
                    var encoding = EncodingDetector.GetEncodingByName(encodingName);
                    var success = await _fileReader.ReloadWithEncodingAsync(encoding);
                    if (success)
                    {
                        // 重新应用字体设置
                        if (_textBlockTextControl != null)
                        {
                            var settings = _settingsService.Settings;
                            var fontFamily = new System.Windows.Media.FontFamily(settings.DefaultFontFamily);
                            var fontSize = settings.DefaultFontSize;
                            var foreground = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                                ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                            var background = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                                ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                            
                            _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                            
                            // 恢复到之前的阅读进度
                            await _textBlockTextControl.LoadPageAsync(currentPageNumber);
                        }
                        
                        // 更新历史记录中的编码信息
                        if (_settingsService.Settings.EnableHistory)
                        {
                            await _historyService.UpdateFileEncodingAsync(_currentFilePath, encoding);
                        }
                        
                        UpdateStatusBar();
                        UpdateEncodingMenuStates();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"切换编码失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async void ChangeEncoding(System.Text.Encoding encoding)
        {
            if (!string.IsNullOrEmpty(_currentFilePath))
            {
                try
                {
                    var success = await _fileReader.ReloadWithEncodingAsync(encoding);
                    if (success)
                    {
                        // 重新应用字体设置
                        if (_textBlockTextControl != null)
                        {
                            var settings = _settingsService.Settings;
                            var fontFamily = new System.Windows.Media.FontFamily(settings.DefaultFontFamily);
                            var fontSize = settings.DefaultFontSize;
                            var foreground = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                                ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                            var background = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                                ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                            
                            _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                        }
                        UpdateStatusBar();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"切换编码失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        #endregion

        #region 搜索操作

        private SearchWindow? _currentSearchWindow;

        /// <summary>
        /// 根据输入参数跳转到指定行
        /// </summary>
        /// <param name="currentLoadedRange">当前文本区载入的行数范围，格式："起始行-结束行"，例如："1-100"</param>
        /// <param name="totalFileLines">文件总行数</param>
        /// <param name="targetLineNumber">要跳转的目标行数</param>
        /// <returns>跳转是否成功</returns>
        public async Task<bool> JumpToLineAsync(string currentLoadedRange, int totalFileLines, int targetLineNumber)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"=== MainWindow.JumpToLineAsync 开始 ===");
                System.Diagnostics.Debug.WriteLine($"当前载入范围: {currentLoadedRange}");
                System.Diagnostics.Debug.WriteLine($"文件总行数: {totalFileLines}");
                System.Diagnostics.Debug.WriteLine($"目标行号: {targetLineNumber}");
                System.Diagnostics.Debug.WriteLine($"目标行号类型: {targetLineNumber.GetType()}");
                System.Diagnostics.Debug.WriteLine($"目标行号值: {targetLineNumber}");

                // 验证输入参数
                if (string.IsNullOrEmpty(currentLoadedRange))
                {
                    System.Diagnostics.Debug.WriteLine("错误: 当前载入范围为空");
                    MessageBox.Show("当前载入范围不能为空", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                if (totalFileLines <= 0)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 文件总行数无效");
                    MessageBox.Show("文件总行数必须大于0", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                if (targetLineNumber <= 0 || targetLineNumber > totalFileLines)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 目标行号超出范围");
                    MessageBox.Show($"目标行号必须在1到{totalFileLines}之间", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                // 解析当前载入范围
                var rangeParts = currentLoadedRange.Split('-');
                if (rangeParts.Length != 2)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 当前载入范围格式不正确");
                    MessageBox.Show("当前载入范围格式不正确，应为：起始行-结束行", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                if (!int.TryParse(rangeParts[0].Trim(), out int currentStartLine) ||
                    !int.TryParse(rangeParts[1].Trim(), out int currentEndLine))
                {
                    System.Diagnostics.Debug.WriteLine("错误: 无法解析当前载入范围");
                    MessageBox.Show("无法解析当前载入范围，请确保格式正确", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                System.Diagnostics.Debug.WriteLine($"解析的当前范围: {currentStartLine}-{currentEndLine}");

                // 检查文本控件是否可用
                if (_textBlockTextControl == null)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 文本控件未初始化");
                    MessageBox.Show("文本控件未初始化", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 检查文件是否打开
                if (!_fileReader.IsFileOpen)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 没有打开的文件");
                    MessageBox.Show("没有打开的文件", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 检查目标行是否在当前载入范围内
                bool isInCurrentRange = targetLineNumber >= currentStartLine && targetLineNumber <= currentEndLine;
                System.Diagnostics.Debug.WriteLine($"目标行是否在当前范围内: {isInCurrentRange}");

                if (isInCurrentRange)
                {
                    // 如果目标行在当前范围内，直接跳转
                    System.Diagnostics.Debug.WriteLine("目标行在当前范围内，直接跳转");
                    await _textBlockTextControl.JumpToLineAsync(targetLineNumber);
                }
                else
                {
                    // 如果目标行不在当前范围内，需要加载新页面
                    System.Diagnostics.Debug.WriteLine("目标行不在当前范围内，需要加载新页面");
                    
                    // 更新文件总行数（如果不同）
                    if (_fileReader.TotalLines != totalFileLines)
                    {
                        System.Diagnostics.Debug.WriteLine($"更新文件总行数: {_fileReader.TotalLines} -> {totalFileLines}");
                        // 这里可能需要更新文件读取器的总行数，但通常不需要手动设置
                    }
                    
                    // 跳转到目标行
                    await _textBlockTextControl.JumpToLineAsync(targetLineNumber);
                }

                System.Diagnostics.Debug.WriteLine("跳转完成");
                
                // 更新状态栏信息
                UpdateStatusBar();
                
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow.JumpToLineAsync Error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 不再显示MessageBox提示，只在调试输出中记录错误
                return false;
            }
            finally
            {
                System.Diagnostics.Debug.WriteLine($"=== MainWindow.JumpToLineAsync 结束 ===");
            }
        }

        /// <summary>
        /// 获取当前文本区载入的行数范围
        /// </summary>
        /// <returns>当前载入范围，格式："起始行-结束行"</returns>
        public string GetCurrentLoadedRange()
        {
            try
            {
                if (_textBlockTextControl == null)
                {
                    return "0-0";
                }

                // 从文本控件获取当前页面信息
                var currentPageNumber = _textBlockTextControl.GetCurrentPageNumber();
                var cacheSize = _textBlockTextControl.GetCacheSize();
                var totalLines = _fileReader.TotalLines;

                var startLine = (currentPageNumber - 1) * cacheSize + 1;
                var endLine = Math.Min(totalLines, startLine + cacheSize - 1);

                return $"{startLine}-{endLine}";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"GetCurrentLoadedRange Error: {ex.Message}");
                return "0-0";
            }
        }

        /// <summary>
        /// 获取文件总行数
        /// </summary>
        /// <returns>文件总行数</returns>
        public int GetTotalFileLines()
        {
            try
            {
                return _fileReader.IsFileOpen ? (int)_fileReader.TotalLines : 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"GetTotalFileLines Error: {ex.Message}");
                return 0;
            }
        }

        /// <summary>
        /// 简化的跳转方法，只需要目标行数作为参数
        /// </summary>
        /// <param name="targetLineNumber">要跳转的目标行数</param>
        /// <returns>跳转是否成功</returns>
        public async Task<bool> JumpToLineAsync(int targetLineNumber)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"=== MainWindow.JumpToLineAsync(简化版) 开始 ===");
                System.Diagnostics.Debug.WriteLine($"目标行号: {targetLineNumber}");
                System.Diagnostics.Debug.WriteLine($"目标行号类型: {targetLineNumber.GetType()}");
                System.Diagnostics.Debug.WriteLine($"目标行号值: {targetLineNumber}");

                // 检查文本控件是否可用
                if (_textBlockTextControl == null)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 文本控件未初始化");
                    MessageBox.Show("文本控件未初始化", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 检查文件是否打开
                if (!_fileReader.IsFileOpen)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 没有打开的文件");
                    MessageBox.Show("没有打开的文件", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 自动获取当前载入范围
                var currentLoadedRange = GetCurrentLoadedRange();
                System.Diagnostics.Debug.WriteLine($"自动获取的当前载入范围: {currentLoadedRange}");

                // 自动获取文件总行数
                var totalFileLines = GetTotalFileLines();
                System.Diagnostics.Debug.WriteLine($"自动获取的文件总行数: {totalFileLines}");

                // 验证目标行号
                if (targetLineNumber <= 0 || targetLineNumber > totalFileLines)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 目标行号超出范围");
                    MessageBox.Show($"目标行号必须在1到{totalFileLines}之间", "参数错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                // 调用完整版跳转方法
                System.Diagnostics.Debug.WriteLine("调用完整版跳转方法...");
                var result = await JumpToLineAsync(currentLoadedRange, totalFileLines, targetLineNumber);
                
                System.Diagnostics.Debug.WriteLine($"简化版跳转结果: {result}");
                
                // 更新状态栏信息
                UpdateStatusBar();
                
                return result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow.JumpToLineAsync(简化版) Error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 不再显示MessageBox提示，只在调试输出中记录错误
                return false;
            }
            finally
            {
                System.Diagnostics.Debug.WriteLine($"=== MainWindow.JumpToLineAsync(简化版) 结束 ===");
            }
        }

        private void OpenSearch()
        {
            if (!_fileReader.IsFileOpen)
            {
                MessageBox.Show("请先打开一个文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var searchEngine = new SearchEngine(_fileReader);
            _currentSearchWindow = new SearchWindow(searchEngine, this);
            _currentSearchWindow.SearchResultSelected += OnSearchResultSelected;
            _currentSearchWindow.Owner = this;
            _currentSearchWindow.Show();
        }

        private void FindNext()
        {
            // TODO: 实现查找下一个
        }

        private void FindPrevious()
        {
            // TODO: 实现查找上一个
        }

        #endregion

        #region 跳转操作

        private void OpenGoToLine()
        {
            // 检查是否有文件打开
            if (!_fileReader.IsFileOpen || _textBlockTextControl == null)
            {
                MessageBox.Show("请先打开一个文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 获取文件总行数
            var totalLines = _textBlockTextControl.GetTotalFileLines();
            if (totalLines <= 0)
            {
                MessageBox.Show("文件为空或无法获取行数", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 检查是否已有跳转窗口打开
            var existingWindow = Application.Current.Windows.OfType<GoToLineWindow>().FirstOrDefault();
            if (existingWindow != null)
            {
                existingWindow.Activate();
                existingWindow.Focus();
                return;
            }

            // 创建跳转窗口
            var goToWindow = new GoToLineWindow(_settingsService, totalLines);
            goToWindow.Owner = this;
            
            // 订阅跳转事件（当用户点击确定时触发）
            goToWindow.GoToRequested += async (lineNumber) =>
            {
                // 立即执行跳转
                await _textBlockTextControl.JumpToLineAsync(lineNumber);
            };

            // 使用Show()而非ShowDialog()，以便窗口保持打开时用户可以操作主窗口
            goToWindow.Show();
        }

        #endregion

        #region 设置操作

        private void OpenSettings()
        {
            var settingsWindow = new SettingsWindow(_settingsService, _historyService);
            settingsWindow.Owner = this;
            
            // 订阅设置更改事件
            settingsWindow.SettingsChanged += OnSettingsChanged;
            
            var result = settingsWindow.ShowDialog();
            
            if (result == true)
            {
                // 只在非历史记录设置更改时应用设置，避免重新载入文本
                // 历史记录设置更改已在 OnSettingsChanged 中处理
                System.Diagnostics.Debug.WriteLine("MainWindow.OpenSettings: 设置窗口关闭，跳过重新应用设置以避免文本重新载入");
            }
        }

        /// <summary>
        /// 设置更改事件处理
        /// </summary>
        private void OnSettingsChanged(object sender, SettingsChangedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"MainWindow.OnSettingsChanged: 设置更改 - 历史记录:{e.HistorySettingChanged}, 字体:{e.FontSettingsChanged}, 颜色:{e.ColorSettingsChanged}, 缓存:{e.CacheSettingsChanged}");
            
            if (e.HistorySettingChanged)
            {
                // 立即更新历史记录菜单
                Dispatcher.Invoke(() =>
                {
                    InitializeHistoryMenu();
                    System.Diagnostics.Debug.WriteLine("MainWindow.OnSettingsChanged: 历史记录菜单已更新");
                    
                    // 如果历史记录从禁用变为启用，且当前有打开的文件，需要重新检查历史记录
                    if (!e.HistoryWasEnabled && e.HistoryNowEnabled && !string.IsNullOrEmpty(_currentFilePath))
                    {
                        System.Diagnostics.Debug.WriteLine($"MainWindow.OnSettingsChanged: 历史记录已启用，重新检查当前文件 {_currentFilePath}");
                        // 异步重新检查历史记录
                        _ = Task.Run(async () =>
                        {
                            try
                            {
                                // 重新添加到历史记录
                                await _historyService.AddFileAsync(_currentFilePath);
                                
                                // 更新历史记录菜单
                                Dispatcher.Invoke(() =>
                                {
                                    InitializeHistoryMenu();
                                    System.Diagnostics.Debug.WriteLine("MainWindow.OnSettingsChanged: 历史记录启用后菜单已更新");
                                });
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine($"MainWindow.OnSettingsChanged: 重新检查历史记录失败 - {ex.Message}");
                            }
                        });
                    }
                });
            }
            
            // 只有在非历史记录设置更改时才应用设置，避免文本重新载入
            if (e.FontSettingsChanged || e.ColorSettingsChanged || e.CacheSettingsChanged || e.WrapLengthChanged || e.StatusBarSettingsChanged)
            {
                System.Diagnostics.Debug.WriteLine("MainWindow.OnSettingsChanged: 应用非历史记录设置更改");
                Dispatcher.Invoke(async () =>
                {
                    var settings = _settingsService.Settings;
                    
                    // 应用所有设置（字体、颜色、缓存、换行等）
                    // 注意：SetWordWrapSettings 只会更新内部状态，不会触发文本重新加载
                    ApplySettings();
                    
                    // 如果换行长度发生变化且当前是按字符数换行模式，需要重新加载当前页面以应用新的换行长度
                    if (e.WrapLengthChanged && _textBlockTextControl != null && _fileReader.IsFileOpen)
                    {
                        if (settings.WordWrapMode == WordWrapMode.Character)
                        {
                            System.Diagnostics.Debug.WriteLine($"MainWindow.OnSettingsChanged: 换行长度已更改，重新加载当前页面以应用新的字符数，新长度={settings.WrapLength}");
                            await _textBlockTextControl.ReloadCurrentPageAsync();
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"MainWindow.OnSettingsChanged: 换行长度已更改，但当前换行模式不是按字符数换行({settings.WordWrapMode})，不更新文本框");
                        }
                    }
                    
                    // 确保状态栏在显示设置更改后立即更新
                    UpdateStatusBar();
                });
            }
        }

        private void ApplySettings()
        {
            var settings = _settingsService.Settings;
            
            System.Diagnostics.Debug.WriteLine($"MainWindow.ApplySettings: 应用设置 - 字体:{settings.DefaultFontFamily}, 大小:{settings.DefaultFontSize}, 换行:{settings.WordWrapMode}, 缓存:{settings.CacheSize}");
            
            // 应用字体设置到TextBlock文本控件
            if (_textBlockTextControl != null)
            {
                var fontFamily = new System.Windows.Media.FontFamily(settings.DefaultFontFamily);
                var fontSize = settings.DefaultFontSize;
                var foreground = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                    ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                var background = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                    ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                
                _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                
               // 应用自动换行设置
               _textBlockTextControl.SetWordWrapSettings(settings.WordWrapMode, settings.WrapLength);
               
               // 应用行号设置
               _textBlockTextControl.SetLineNumberSettings(settings.ShowLineNumbers);
               
               // 应用缓存设置
               _textBlockTextControl.SetCacheSettings(
                   settings.CacheSize, 
                   settings.PreloadPagesBefore, 
                   settings.PreloadPagesAfter
               );
                
                System.Diagnostics.Debug.WriteLine("MainWindow.ApplySettings: 设置已应用到文本控件");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("MainWindow.ApplySettings: _textBlockTextControl 为 null");
            }
            
            // 更新状态栏
            UpdateStatusBar();
        }

        #endregion

        #region 事件处理

        private async void OnFileOpened(object sender, FileOpenedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 开始处理文件打开事件 {e.FilePath}");
            
            // 设置当前文件路径
            _currentFilePath = e.FilePath;
            
            Dispatcher.Invoke(() =>
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 更新状态栏");
                UpdateStatusBar();
            });

            // 加载文本内容
            if (_textBlockTextControl != null)
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 开始加载文本内容");
                try
                {
                    // 首先设置文件读取器
                    System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 设置文件读取器");
                    await _textBlockTextControl.SetFileReaderAsync(_fileReader);
                    
                    // 应用当前字体设置
                    var settings = _settingsService.Settings;
                    var fontFamily = new System.Windows.Media.FontFamily(settings.DefaultFontFamily);
                    var fontSize = settings.DefaultFontSize;
                    var foreground = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                        ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                    var background = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                        ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                    
                    _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                    
                    // 检查并应用历史记录进度
                    await CheckAndApplyHistoryProgressAsync(e.FilePath);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 加载文本内容失败 - {ex.GetType().Name}: {ex.Message}");
                    System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 堆栈跟踪 - {ex.StackTrace}");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: _textBlockTextControl 为 null，无法加载文本内容");
            }
            
            System.Diagnostics.Debug.WriteLine($"MainWindow.OnFileOpened: 文件打开事件处理完成");
        }

        private async void OnEncodingChanged(object sender, EncodingChangedEventArgs e)
        {
            await Dispatcher.InvokeAsync(async () =>
            {
                // 重新应用字体设置
                if (_textBlockTextControl != null)
                {
                    var settings = _settingsService.Settings;
                    var fontFamily = new System.Windows.Media.FontFamily(settings.DefaultFontFamily);
                    var fontSize = settings.DefaultFontSize;
                    var foreground = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultForegroundColor) is System.Windows.Media.Color fgColor 
                        ? new System.Windows.Media.SolidColorBrush(fgColor) : System.Windows.Media.Brushes.Black;
                    var background = System.Windows.Media.ColorConverter.ConvertFromString(settings.DefaultBackgroundColor) is System.Windows.Media.Color bgColor 
                        ? new System.Windows.Media.SolidColorBrush(bgColor) : System.Windows.Media.Brushes.White;
                    
                    _textBlockTextControl.UpdateFontSettings(fontFamily, fontSize, foreground, background);
                }
                UpdateStatusBar();
            });
        }

        #endregion

        #region 其他操作


        private async void OnSearchResultSelected(object sender, SearchResultSelectedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"=== OnSearchResultSelected 开始 ===");
            System.Diagnostics.Debug.WriteLine($"搜索结果行号: {e.SearchResult.LineNumber}");
            System.Diagnostics.Debug.WriteLine($"搜索结果列号: {e.SearchResult.ColumnIndex}");
            System.Diagnostics.Debug.WriteLine($"搜索结果内容: {e.SearchResult.Content}");
            
            try
            {
                if (_textBlockTextControl == null)
                {
                    System.Diagnostics.Debug.WriteLine("错误: _textBlockTextControl 为 null");
                    MessageBox.Show("文本控件未初始化", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                
                if (!_fileReader.IsFileOpen)
                {
                    System.Diagnostics.Debug.WriteLine("错误: 没有打开的文件");
                    MessageBox.Show("没有打开的文件", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                
                System.Diagnostics.Debug.WriteLine("开始调用 JumpToLineAsync...");
                
                // 只传递目标行号，让主窗口负责计算页面范围和跳转控制
                await _textBlockTextControl.JumpToLineAsync(e.SearchResult.LineNumber);
                
                System.Diagnostics.Debug.WriteLine("JumpToLineAsync 调用完成");
                
                // 不关闭搜索窗口，让用户可以继续搜索其他内容
                
                // 不再显示成功消息，只在调试输出中记录
                System.Diagnostics.Debug.WriteLine($"已跳转到第 {e.SearchResult.LineNumber} 行");
                
                System.Diagnostics.Debug.WriteLine("跳转完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"OnSearchResultSelected Error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 不再显示MessageBox提示，只在调试输出中记录错误
            }
            finally
            {
                System.Diagnostics.Debug.WriteLine($"=== OnSearchResultSelected 结束 ===");
            }
        }

        #endregion

        #region 滚动条事件处理

        private void OnScrollBarValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // TODO: 实现滚动条值改变处理
        }

        /// <summary>
        /// 文本控件滚动事件处理
        /// </summary>
        private void OnTextControlScrolled(object sender, EventArgs e)
        {
            // 触发防抖定时器，延迟保存阅读进度
            _scrollDebounceTimer.Change(ScrollDebounceDelay, Timeout.Infinite);
        }

        /// <summary>
        /// 鼠标滚轮事件处理（已弃用，改为使用OnTextControlScrolled）
        /// </summary>
        private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        {
            // 触发防抖定时器，延迟保存阅读进度
            _scrollDebounceTimer.Change(ScrollDebounceDelay, Timeout.Infinite);
        }

        /// <summary>
        /// 滚动防抖定时器触发
        /// </summary>
        private async void OnScrollDebounceTimerElapsed(object? state)
        {
            // 在UI线程中执行
            await Dispatcher.InvokeAsync(async () =>
            {
                try
                {
                    await UpdateHistoryPositionAsync();
                    System.Diagnostics.Debug.WriteLine($"滚动防抖: 已保存阅读进度");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"滚动防抖保存进度失败: {ex.Message}");
                }
            });
        }

        #region 换行策略菜单事件处理

        /// <summary>
        /// 不自动换行菜单项点击事件
        /// </summary>
        private async void OnNoWrapMenuClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("MainWindow.OnNoWrapMenuClick: 切换到不自动换行模式");
            _textBlockTextControl?.SetWordWrapSettings(WordWrapMode.None, 0);
            UpdateWordWrapMenuStates(WordWrapMode.None);
            
            // 重新加载当前页面以立即应用换行设置
            if (_textBlockTextControl != null && _fileReader.IsFileOpen)
            {
                await _textBlockTextControl.ReloadCurrentPageAsync();
            }
        }

        /// <summary>
        /// 按窗口宽度换行菜单项点击事件
        /// </summary>
        private async void OnWindowWrapMenuClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("MainWindow.OnWindowWrapMenuClick: 切换到按窗口宽度换行模式");
            _textBlockTextControl?.SetWordWrapSettings(WordWrapMode.Window, 0);
            UpdateWordWrapMenuStates(WordWrapMode.Window);
            
            // 重新加载当前页面以立即应用换行设置
            if (_textBlockTextControl != null && _fileReader.IsFileOpen)
            {
                await _textBlockTextControl.ReloadCurrentPageAsync();
            }
        }

        /// <summary>
        /// 按字符数换行菜单项点击事件
        /// </summary>
        private async void OnCharacterWrapMenuClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("MainWindow.OnCharacterWrapMenuClick: 切换到按字符数换行模式");
            // 使用设置中的字符数，如果没有设置则使用默认值80
            var wrapLength = _settingsService.Settings.WrapLength > 0 ? _settingsService.Settings.WrapLength : 80;
            _textBlockTextControl?.SetWordWrapSettings(WordWrapMode.Character, wrapLength);
            UpdateWordWrapMenuStates(WordWrapMode.Character);
            
            // 重新加载当前页面以立即应用换行设置
            if (_textBlockTextControl != null && _fileReader.IsFileOpen)
            {
                await _textBlockTextControl.ReloadCurrentPageAsync();
            }
        }

        /// <summary>
        /// 更新换行策略菜单项的选中状态
        /// </summary>
        /// <param name="currentMode">当前的换行模式</param>
        private void UpdateWordWrapMenuStates(WordWrapMode currentMode)
        {
            // 更新菜单项的选中状态
            if (FindName("NoWrapMenuItem") is MenuItem noWrapMenuItem)
            {
                noWrapMenuItem.IsChecked = currentMode == WordWrapMode.None;
            }

            if (FindName("WindowWrapMenuItem") is MenuItem windowWrapMenuItem)
            {
                windowWrapMenuItem.IsChecked = currentMode == WordWrapMode.Window;
            }

            if (FindName("CharacterWrapMenuItem") is MenuItem characterWrapMenuItem)
            {
                characterWrapMenuItem.IsChecked = currentMode == WordWrapMode.Character;
            }

            System.Diagnostics.Debug.WriteLine($"MainWindow.UpdateWordWrapMenuStates: 更新菜单状态，当前模式 = {currentMode}");
        }

        #endregion

        #endregion

        /// <summary>
        /// 设置窗口图标（从main.ico文件加载）
        /// </summary>
        private void SetWindowIcon()
        {
            try
            {
                // 优先从可执行文件同目录加载
                var exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                var exeDir = System.IO.Path.GetDirectoryName(exePath);
                
                if (exeDir != null)
                {
                    var iconPath = System.IO.Path.Combine(exeDir, "main.ico");
                    if (System.IO.File.Exists(iconPath))
                    {
                        using (var iconStream = new System.IO.FileStream(iconPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        using (var icon = new System.Drawing.Icon(iconStream))
                        {
                            Icon = Imaging.CreateBitmapSourceFromHIcon(
                                icon.Handle,
                                Int32Rect.Empty,
                                BitmapSizeOptions.FromEmptyOptions());
                            return;
                        }
                    }
                }
                
                // 如果exe目录没有，尝试从AppDomain.BaseDirectory查找
                var baseDir = AppDomain.CurrentDomain.BaseDirectory;
                var baseIconPath = System.IO.Path.Combine(baseDir, "main.ico");
                if (System.IO.File.Exists(baseIconPath))
                {
                    using (var iconStream = new System.IO.FileStream(baseIconPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    using (var icon = new System.Drawing.Icon(iconStream))
                    {
                        Icon = Imaging.CreateBitmapSourceFromHIcon(
                            icon.Handle,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"设置窗口图标失败: {ex.Message}");
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            _fileReader?.Dispose();
            _scrollDebounceTimer?.Dispose();
            base.OnClosed(e);
        }
    }

    /// <summary>
    /// 简单的命令实现
    /// </summary>
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool>? _canExecute;

        public RelayCommand(Action execute, Func<bool>? canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object? parameter)
        {
            return _canExecute?.Invoke() ?? true;
        }

        public void Execute(object? parameter)
        {
            _execute();
        }
    }
}

